﻿using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Mvc.Rendering
{
    public static class HtmlHelperExtension
    {

        /// <summary>
        /// asp.net core Html.DisplayFor已经由此功能，这个似乎用不上了
        /// </summary>
        /// <param name="html"></param>
        /// <param name="eum"></param>
        /// <returns></returns>
        public static string DisplayEnumName(this IHtmlHelper html, Enum eum)
        {
            var type = eum.GetType();//先获取这个枚举的类型
            var field = type.GetField(eum.ToString());//通过这个类型获取到值
            var obj = (DisplayAttribute)field.GetCustomAttribute(typeof(DisplayAttribute));//得到特性
            return obj.Name ?? "";
        }

        public static IEnumerable<SelectListItem> GetEnumSelectList<TEnum>(this IHtmlHelper html,int enumValue) where TEnum : struct
        {
            
            var type = typeof(TEnum);
            
            var values = Enum.GetValues(type);
            List<SelectListItem> list = new List<SelectListItem>();
            
            foreach(var value in values)
            {
                int enumNum = (int)value;
                if((enumNum | enumValue)==enumValue)
                {
                    var field = type.GetField(value.ToString());
                    var obj = (DisplayAttribute)field.GetCustomAttribute(typeof(DisplayAttribute));
                    SelectListItem item = new SelectListItem(obj.Name ?? "", ((int)value).ToString());
                    list.Add(item);
                }
                

            }
            
            return list;
        }
    }
}
